<script setup lang="ts">
import { computed } from 'vue'

interface MessageContent {
  data?: string;
  [key: string]: any;
}

const props = defineProps<{
  content: string | MessageContent;
  sender: string;
  timestamp?: number;
}>()

const messageClass = computed(() => {
  return {
    'message-container': true,
    'user-message': props.sender === 'user',
    'system-message': props.sender === 'system',
    'assistant-message': props.sender === 'assistant'
  }
})

const senderClass = computed(() => {
  return {
    'message-sender': true,
    'user-sender': props.sender === 'user',
    'system-sender': props.sender === 'system',
    'assistant-sender': props.sender === 'assistant'
  }
})

const formattedTimestamp = computed(() => {
  if (!props.timestamp) return ''
  const date = new Date(props.timestamp)
  return date.toLocaleString()
})

const formattedContent = computed(() => {
  if (typeof props.content === 'object' && props.content !== null) {
    // If it's an object with a data property, just show the data
    if ('data' in props.content && props.content.data) {
      return props.content.data
    }
    return JSON.stringify(props.content, null, 2)
  }
  return String(props.content || '')
})

const hasNewlines = computed(() => {
  return formattedContent.value.includes('\n')
})
</script>

<template>
  <div :class="messageClass">
    <div :class="senderClass">
      {{ sender }}
      <span v-if="timestamp" class="timestamp">{{ formattedTimestamp }}</span>
    </div>
    <div class="message-content">
      <pre v-if="hasNewlines">{{ formattedContent }}</pre>
      <span v-else>{{ formattedContent }}</span>
    </div>
  </div>
</template>

<style scoped>
.message-container {
  margin: 10px 0;
  padding: 10px;
  border-radius: 8px;
  max-width: 80%;
}

.user-message {
  background-color: #e3f2fd;
  margin-left: auto;
  text-align: right;
}

.system-message {
  background-color: #f5f5f5;
  margin-right: auto;
}

.assistant-message {
  background-color: #f1f8e9;
  margin-right: auto;
}

.message-sender {
  font-weight: bold;
  margin-bottom: 5px;
  display: block;
  align-items: center;
  justify-content: space-between;
}

.user-sender {
  color: #1976d2;
}

.system-sender {
  color: #616161;
}

.assistant-sender {
  color: #689f38;
}

.timestamp {
  font-size: 0.8em;
  color: #757575;
  font-weight: normal;
  margin-left: 8px;
}

.message-content {
  white-space: pre-wrap;
  word-wrap: break-word;
  text-align: left;
}

.user-message .message-content {
  text-align: right;
}

.message-content pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: inherit;
}
</style>